// 登录。根据用户账户+密码+身份，获取用户信息和加入的班级信息
import express from 'express';
import pool from "../importantApi/db_connection.js";

const router = express.Router();
router.post('/', async (req, res) => {
    const {account, password, identity} = req.body;
    if (!account || !password || !identity) {
        return res.status(401).json({
            code: 401,
            msg: "缺少登录信息"
        });
    }
    try {
        let sql =`
            select u.user_id,
                   u.user_name,
                   u.createtime,
                   u.identity,
                   MAX(CASE WHEN uc.class_id IS NOT NULL THEN 1 ELSE 0 END) AS hasJoinClass
            from userinfo u
                     left join user_class uc
                               on u.user_id = uc.user_id
            where u.account = '${account}'
              and u.password = '${password}'
              and u.identity = '${identity}'
            group by u.user_id
        `
        let [result] = await pool.query(sql);
        if (result.length > 0) {
          return  res.status(200).json({
                code: 200,
                msg: "登录成功",
                data: result[0]
            })
        } else {
            res.status(201).json({
                code: 201,
                msg: "登录信息不匹配"
            })
        }
    } catch (err) {
        return res.status(500).json({
            code: 500,
            error: err,
            msg: "登录错误：server error"
        })
    }
})
export default router;